package com.caishichang.infosysdesign.controller.user;

import com.caishichang.infosysdesign.config.Constants;
import com.caishichang.infosysdesign.entity.Strategy;
import com.caishichang.infosysdesign.service.StrategyService;
import com.caishichang.infosysdesign.util.PageQueryUtil;
import com.caishichang.infosysdesign.util.Result;
import com.caishichang.infosysdesign.util.ResultGenerator;
import com.caishichang.infosysdesign.util.SystemUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;

@Controller
@RequestMapping("/user/strategy")
public class UserStrategyController {

    @Autowired
    StrategyService strategyService;

    /**
     * 进入【攻略管理页面】(
     * <p>
     * （ 注：进入攻略管理页面，必须要登录）
     * </p>
     *
     * @return
     */
    @RequestMapping({"", "/"})
    public String manageStrategy(HttpServletRequest request) {
        request.setAttribute("path", "攻略管理");
        return "user/strategy/strategy";
    }

    /**
     * 进入【新增攻略页面】
     *
     * @return
     */
    @GetMapping("/addStrategy")
    public String addStrategyPage(HttpServletRequest request, HttpSession session) {
        request.setAttribute("path", "添加攻略");
        return "user/strategy/edit";
    }

    /**
     * 进入【修改攻略页面】
     *
     * @return
     */
    @GetMapping("/updateStrategy{strategyId}")
    public String updateStrategyPage(HttpServletRequest request, @PathVariable("strategyId") Long strategyId) {
        request.setAttribute("path", "修改攻略");
        Strategy strategy = strategyService.getStrategy(strategyId);
        if (strategy == null) {
            return "error/error_400";
        }
        request.setAttribute("strategy", strategy);
        return "user/strategy/edit";
    }

    /**
     * 新建攻略
     *
     * @param strategyTitle      攻略标题
     * @param strategyContent    攻略内容
     * @param strategyStatus     攻略状态
     * @param strategyCoverImage 攻略封面
     * @return
     */
    @PostMapping(value = "/addStrategy/add")
    @ResponseBody
    public Result addStrategy(HttpSession session,
                              @RequestParam("strategyTitle") String strategyTitle,
                              @RequestParam("strategyContent") String strategyContent,
                              @RequestParam("strategyStatus") Integer strategyStatus,
                              @RequestParam("strategyCoverImage") String strategyCoverImage
    ) {
        // 处理日常情况
        if (StringUtils.isEmpty(strategyTitle))
            return ResultGenerator.genFailResult("请输入文章标题");

        if (strategyTitle.trim().length() > 150)
            return ResultGenerator.genFailResult("标题过长");

        if (StringUtils.isEmpty(strategyContent)) {
            return ResultGenerator.genFailResult("请输入文章内容");
        }
        if (strategyContent.trim().length() > 100000) {
            return ResultGenerator.genFailResult("文章内容过长");
        }
        if (StringUtils.isEmpty(strategyCoverImage)) {
            return ResultGenerator.genFailResult("封面图不能为空");
        }

        Strategy strategy = new Strategy();
        strategy.setStrategyTitle(strategyTitle);
        strategy.setStrategyContent(strategyContent);
        strategy.setStrategyCoverImage(strategyCoverImage);
        strategy.setStrategyStatus(strategyStatus);

        // 返回结果
        if (strategyService.insertStrategy(strategy))
            return ResultGenerator.genSuccessResult("发布成功");
        else
            return ResultGenerator.genFailResult("发布失败");
    }

    /**
     * 更新攻略
     *
     * @param strategyId      攻略id
     * @param strategyTitle   攻略标题
     * @param strategyContent 攻略内容
     * @return 攻略默认页面（成功）/ 操作失败页面（失败）
     */
    @PostMapping(value = "/updateStrategy/update")
    @ResponseBody
    public Result updateStrategy(@RequestParam("") Long strategyId,
                                 @RequestParam("") String strategyTitle,
                                 @RequestParam("") String strategyContent) {

        // 处理异常情况
        if (StringUtils.isEmpty(strategyTitle))
            return ResultGenerator.genFailResult("请输入文章标题");

        if (strategyTitle.trim().length() > 150)
            return ResultGenerator.genFailResult("标题过长");

        if (StringUtils.isEmpty(strategyContent)) {
            return ResultGenerator.genFailResult("请输入文章内容");
        }
        if (strategyContent.trim().length() > 100000) {
            return ResultGenerator.genFailResult("文章内容过长");
        }

        Strategy strategy = new Strategy();
        strategy.setStrategyId(strategyId);
        strategy.setStrategyTitle(strategyTitle);
        strategy.setStrategyContent(strategyContent);

        // 返回结果
        if (strategyService.updateStrategy(strategy))
            return ResultGenerator.genSuccessResult("修改成功");
        else
            return ResultGenerator.genFailResult("修改失败");
    }

    /**
     * 上传封面图片
     *
     * @param request
     * @param response
     * @param file
     * @throws IOException
     * @throws URISyntaxException
     */
    @PostMapping("/md/uploadfile")
    public void uploadFileByEditormd(HttpServletRequest request,
                                     HttpServletResponse response,
                                     @RequestParam(name = "editormd-image-file", required = true)
                                             MultipartFile file) throws IOException, URISyntaxException {
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //生成文件名称通用方法
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        Random r = new Random();
        StringBuilder tempName = new StringBuilder();
        tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
        String newFileName = tempName.toString();
        //创建文件
        File destFile = new File(Constants.FILE_UPLOAD_DIC + newFileName);
        String fileUrl = SystemUtil.getHost(new URI(request.getRequestURL() + "")) + "/upload/" + newFileName;
        File fileDirectory = new File(Constants.FILE_UPLOAD_DIC);
        try {
            if (!fileDirectory.exists()) {
                if (!fileDirectory.mkdir()) {
                    throw new IOException("文件夹创建失败,路径为：" + fileDirectory);
                }
            }
            file.transferTo(destFile);
            request.setCharacterEncoding("utf-8");
            response.setHeader("Content-Type", "text/html");
            response.getWriter().write("{\"success\": 1, \"message\":\"success\",\"url\":\"" + fileUrl + "\"}");
        } catch (UnsupportedEncodingException e) {
            response.getWriter().write("{\"success\":0}");
        } catch (IOException e) {
            response.getWriter().write("{\"success\":0}");
        }
    }

    /**
     * @param params
     * @return
     */
    @GetMapping("/list")
    @ResponseBody
    public Result list(@RequestParam Map<String, Object> params) {
        if (StringUtils.isEmpty(params.get("page")) || StringUtils.isEmpty(params.get("limit"))) {
            return ResultGenerator.genFailResult("参数异常！");
        }
        PageQueryUtil pageUtil = new PageQueryUtil(params);
        return ResultGenerator.genSuccessResult(strategyService.getStrategiesPage(pageUtil));
    }

    /**
     * 删除单个（或多个）攻略
     *
     * @param ids 需要删除的攻略id
     * @return
     */
    @PostMapping("/delete")
    @ResponseBody
    public Result delete(@RequestBody Long[] ids) {
        if (ids.length < 1) {
            return ResultGenerator.genFailResult("参数异常！");
        }
        if (strategyService.deleteStrategy(ids)) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult("删除失败");
        }
    }
}
